package plugin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.File;

/**
 * This class is responsible for parsing and extracting data out of the config file.
 * @author Royce
 *
 */
public class ConfigProcessor {

	private final String DEFAULT_LOC = "plugins.xml";
	
	/**
	 * Default no-arg constructor
	 */
	public ConfigProcessor() {
		
	}
	
	/**
	 * Extracts all PluginDescriptors out of the default config file.
	 * @return A list of all extracted PluginDescriptors.
	 * @throws IOException if unable to read from the file, or if the file is malformed.
	 */
	public List<PluginDescriptor> parseConfig() throws IOException {
		return parseConfig(DEFAULT_LOC);
	}
	
	/**
	 * Extracts all PluginDescriptors out of the given config file location.
	 * @param fileName the location of the file relative to HIT's working directory
	 * @return the parsed out list of PluginDescriptors
	 * @throws IOException if unable to load or read the given file.
	 */
	public List<PluginDescriptor> parseConfig(String fileName) throws IOException {
		List<PluginDescriptor> descList = new ArrayList<PluginDescriptor>();
		try {
			File pluginFile = new File(fileName);
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(pluginFile);
			doc.getDocumentElement().normalize();
			NodeList nList = doc.getElementsByTagName("plugin");
			int numPlugins = nList.getLength();
			for (int i = 0; i < numPlugins; i++) {
				Node nNode = nList.item(i);
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element)nNode;
					String cClass = eElement.getAttribute("class");
					PluginDescriptor newDesc = new PluginDescriptor(cClass);
					descList.add(newDesc);
				}
			}
		}
		catch (SAXException | ParserConfigurationException e) {
			e.printStackTrace();
			throw new IOException("Malformed file!");
		}
		
		return descList;
	}
	
}
